package com.jiali.backend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiali.backend.Utils.FileUploadUtil;
import com.jiali.backend.Utils.UserServiceUtils;
import com.jiali.backend.common.ResponseResult;
import com.jiali.backend.controller.request.StaffAddRequest;
import com.jiali.backend.controller.request.StaffUpdateRequest;
import com.jiali.backend.mapper.StaffMapper;
import com.jiali.backend.model.Staff;
import com.jiali.backend.service.StaffService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * @author piko
 * @description 针对表【staff(员工表)】的数据库操作Service实现
 * @createDate 2025-03-27 15:33:51
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff>
        implements StaffService {
    @Value("${file.upload-dir}")
    private String uploadDir;
    @Resource
    private UserServiceUtils userServiceUtils;

    //查询所有员工
    @Override
    public ResponseResult<List<Staff>> getAllStaffs(HttpServletRequest request) {
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        if (!userServiceUtils.IsAdmin(request)) {
            return ResponseResult.fail(403, "无权限查看员工列表", null);
        }

        List<Staff> staffs = this.list();
        staffs.forEach(Staff::getFormattedEntryDate); // 触发格式化
        return ResponseResult.success(staffs);
    }

    //查询单个员工-按名称
    @Override
    public ResponseResult<List<Staff>> searchStaffsByName(String name, HttpServletRequest request) {
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        if (!userServiceUtils.IsAdmin(request)) {
            return ResponseResult.fail(403, "无权限搜索员工", null);
        }

        List<Staff> staffs = this.lambdaQuery()
                .like(Staff::getName, name)
                .list();
        staffs.forEach(Staff::getFormattedEntryDate); // 触发格式化
        return ResponseResult.success(staffs);
    }

    //按照id删除
    @Override
    public ResponseResult<Boolean> deleteStaffById(Integer id, HttpServletRequest request) {
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        if (!userServiceUtils.IsAdmin(request)) {
            return ResponseResult.fail(403, "无权限删除员工", null);
        }

        boolean result = this.removeById(id);
        return ResponseResult.success(200, "OK", result);
    }

    //按照id查询员工
    @Override
    public ResponseResult<Staff> getStaffById(Integer id, HttpServletRequest request) {
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        if (!userServiceUtils.IsAdmin(request)) {
            return ResponseResult.fail(403, "无权限查看员工详情", null);
        }

        Staff staff = this.getById(id);
        if (staff != null) {
            staff.getFormattedEntryDate(); // 触发格式化
            return ResponseResult.success(200, "OK", staff);
        }
        return ResponseResult.fail(404, "员工不存在", null);
    }

    //新增员工
    @Override
    public ResponseResult<Staff> addStaff(StaffAddRequest staffAddRequest, HttpServletRequest request) {
        // 权限验证
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        if (!userServiceUtils.IsAdmin(request)) {
            return ResponseResult.fail(403, "无权限添加员工", null);
        }

        // 创建员工对象
        Staff staff = new Staff();
        staff.setName(staffAddRequest.getName());
        staff.setPosition(staffAddRequest.getPosition());
        // 处理照片上传 (这里需要实现文件上传逻辑)
        if (staffAddRequest.getPhoto() != null) {
            try {
                // 直接处理文件上传逻辑
                String contentType = staffAddRequest.getPhoto().getContentType();
                if (!"image/jpeg".equals(contentType)
                        && !"image/png".equals(contentType)
                        && !"image/gif".equals(contentType)) {
                    return ResponseResult.fail(400, "只支持JPEG/PNG/GIF格式的图片", null);
                }

                // 调用工具类保存文件
                String filename = FileUploadUtil.saveFile(staffAddRequest.getPhoto(), uploadDir + "/photo/staff/");
                String photoUrl = "http://localhost:8080/upload/photo/staff/" + filename;
                staff.setPhoto(photoUrl);

            } catch (Exception e) {
                return ResponseResult.fail(500, "头像更新失败: " + e.getMessage(), null);
            }
        }
        // 保存员工获取ID
        this.save(staff);
        // 设置工号(10000+id)
        staff.setJobNumber(String.valueOf(10000 + staff.getId()));
        staff.setDescription(staffAddRequest.getDescription());
        // 更新员工信息(包含工号)
        this.updateById(staff);
        return ResponseResult.success(staff);
    }

    @Override
    public ResponseResult<Staff> updateStaff(StaffUpdateRequest staffUpdateRequest, HttpServletRequest request) {
        // 权限验证
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        if (!userServiceUtils.IsAdmin(request)) {
            return ResponseResult.fail(403, "无权限修改员工信息", null);
        }

        Staff staff = this.getById(staffUpdateRequest.getId());
        if (staff == null) {
            return ResponseResult.fail(404, "员工不存在", null);
        }

        // 更新基础信息
        staff.setName(staffUpdateRequest.getName());
        staff.setPosition(staffUpdateRequest.getPosition());
        staff.setDescription(staffUpdateRequest.getDescription());

        // 处理照片更新
        if (staffUpdateRequest.getPhoto() != null && !staffUpdateRequest.getPhoto().isEmpty()) {
            try {
                String contentType = staffUpdateRequest.getPhoto().getContentType();
                assert contentType != null;
                if (!contentType.startsWith("image/")) {
                    return ResponseResult.fail(400, "只支持图片格式文件", null);
                }

                String filename = FileUploadUtil.saveFile(staffUpdateRequest.getPhoto(), uploadDir + "/photo/staff/");
                String newPhotoUrl = "http://localhost:8080/upload/photo/staff/" + filename;
                staff.setPhoto(newPhotoUrl);
            } catch (Exception e) {
                return ResponseResult.fail(500, "照片更新失败: " + e.getMessage(), null);
            }
        }

        this.updateById(staff);
        return ResponseResult.success(staff);
    }

    @Override
    public ResponseResult<List<Staff>> getStaffsByPosition(Integer position, HttpServletRequest request) {
        // 权限验证
        if (userServiceUtils.IsAdmin(request) == null) {
            return ResponseResult.fail(401, "用户未登录", null);
        }
        if (!userServiceUtils.IsAdmin(request)) {
            return ResponseResult.fail(403, "无权限查看员工列表", null);
        }

        List<Staff> staffs = this.lambdaQuery()
                .eq(Staff::getPosition, position)
                .list();
        staffs.forEach(Staff::getFormattedEntryDate); // 触发格式化
        return ResponseResult.success(200, "OK", staffs);
    }
}


